from typing_extensions import Annotated,List

from fastapi import Request, HTTPException, Path
from sqlalchemy import select

from core.database import db_session
from core.models import Board, Group
from lib.member import MemberDetails
from . import BoardService


class GroupBoardListService(BoardService):
    """
    用于获取组的公告板列表的类
    """

    def __init__(
        self,
        request: Request,
        db: db_session,
        gr_id: Annotated[str, Path(...)],
    ):
        self.request = request
        self.db = db
        self.gr_id = gr_id
        self.group = self.get_group()
        self.member = MemberDetails(request, request.state.login_member, group=self.group)

    @classmethod
    async def async_init(
        cls,
        request: Request,
        db: db_session,
        gr_id: Annotated[str, Path(...)],
    ):
        instance = cls(request, db, gr_id)
        return instance

    def get_group(self) -> Group:
        """公告组信息查询"""
        group = self.db.get(Group, self.gr_id)
        if not group:
            self.raise_exception(detail=f"{self.gr_id} : 这是一个不存在的公告板组.", status_code=404)
        return group

    def check_mobile_only(self):
        """检查它是否是仅限移动设备的公告板"""
        # FIXME: 移动电话/PC 季度处理
        if self.member.admin_type:
            return
        if self.request.state.device == "mobile":
            self.raise_exception(detail=f"{self.group.gr_subject} 只能从移动设备访问组.", status_code=403)

    def get_boards_in_group(self) -> List[Board]:
# # “查看属于公告栏组的公告栏列表”
# 查看分组公告栏列表
        query = (
            select(Board)
            .where(
                Board.gr_id == self.gr_id,
                Board.bo_list_level <= self.member.level,
                Board.bo_device != 'mobile'
            )
            .order_by(Board.bo_order)
        )
        # Exclut认证公告板
        if not self.member.admin_type:
            query = query.filter_by(bo_use_cert="")

        boards = self.db.scalars(query).all()
        return boards